package cn.hfjava.kz.service.impl;

import cn.hfjava.kz.common.listener.PublicReadExcelListener;
import cn.hfjava.kz.entity.excel.StudentExcel;
import cn.hfjava.kz.entity.po.Student;
import cn.hfjava.kz.mapper.StudentMapper;
import cn.hfjava.kz.service.StudentService;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

/**
 * 考生业务逻辑接口的实现类
 * @author lds
 */
@Service(value = "studentService") // 表示在Spring容器中注册一个考生业务Bean
@Transactional(
        rollbackFor = {Exception.class}
)
public class StudentServiceImpl
        extends ServiceImpl<StudentMapper, Student>
        implements StudentService {
    private final static List<String> EXCEL_SUFFIX = Arrays.asList("xls","xlsx");

    @Resource
    private StudentMapper studentMapper;


    @Transactional(readOnly = true,
            propagation = Propagation.SUPPORTS,
            isolation = Isolation.REPEATABLE_READ)
    @Override
    public List<StudentExcel> findStudentExcelByIdList(List<Integer> idList) {
        return studentMapper.getStudentExcelByIds(idList);
    }

    @Override
    public Integer addBatchStudents(List<StudentExcel> list) {
        return studentMapper.batchInsert(list);
    }

    @Override
    public void importDataByExcel(MultipartFile file) {
        String filename = file.getOriginalFilename();
        //Assert.notNull(filename,"文件名称不能为空");
        String suffix = filename.substring(filename.lastIndexOf(".")+1);
        if (!EXCEL_SUFFIX.contains(suffix)){
            throw new RuntimeException("上传的文件不是Excel文件!");
        }
        try (InputStream ism = file.getInputStream()){
            EasyExcel.read(ism,Student.class,new PublicReadExcelListener<>(this,1000)).sheet(0).headRowNumber(2).doRead();
        }catch (Exception ex){
            log.error("导入文件【"+filename+"】报错：",ex);
            ex.printStackTrace();
        }
    }

    @Override
    public Integer recoverById(Integer id) {
      return   studentMapper.recoverById(id);
    }
    @Override
    public Integer batchRecoverById(List<Integer> idList) {
        return studentMapper.batchRecoverById(idList);
    }

    @Override
    public List<Integer> findByIdAll() {
        return studentMapper.findIdAll();
    }
}
